package com.xywl.escort.view.market.skus;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

import com.makeramen.roundedimageview.RoundedImageView;
import com.xywl.escort.R;
import com.xywl.escort.bean.BaseSkuModel;
import com.xywl.escort.utils.NumberFormatUtils;
import com.xywl.escort.utils.ToastUtil;
import com.xywl.escort.widget.GlideApp;

public class BodyPopWindow implements OnDismissListener, OnClickListener, onViewChange {

    private StateButton pop_ok;
    private StateButton btn_buy;
    private StateButton btn_confirm;
    private PopupWindow popupWindow;
    private OnItemClickListener listener;
    private Context context;
    private ImageView popDel;
    private RecyclerView recyclerView;
    private CountChooseAdapter mAdapter;
    private UiData mUiData;
    private RoundedImageView select_iv;

    private TextView select_price_tv;
    private TextView textOriginalPrice;
    private TextView Stock_tv;
    private TextView choose_title;
    private int mType;
    private boolean isAllChoose;
    private boolean mIsSpecSmall;

    public BodyPopWindow(Context context, UiData mUIData, int type, boolean isSpecSmall) {
        this.context = context;
        View view = LayoutInflater.from(context).inflate(R.layout.shop_tab_dialog, null);
        mUiData = mUIData;
        mType = type;
        mIsSpecSmall = isSpecSmall;
        configView(view);
        configPopWindow(view);
    }

    private void darkenBackground(Float bgColor) {
        WindowManager.LayoutParams lp = ((Activity) context).getWindow().getAttributes();
        lp.alpha = bgColor;
        ((Activity) context).getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        ((Activity) context).getWindow().setAttributes(lp);
    }

    /**
     * 获取view实例及设置监听
     *
     * @param view
     */
    private void configView(View view) {
        pop_ok = view.findViewById(R.id.pop_ok);
        btn_buy = view.findViewById(R.id.btn_buy);
        btn_confirm = view.findViewById(R.id.btn_confirm);
        popDel = view.findViewById(R.id.close);
        select_iv = view.findViewById(R.id.select_iv);

        switch (mType) {
            case 1:
                pop_ok.setVisibility(View.VISIBLE);
                btn_buy.setVisibility(View.VISIBLE);
                btn_confirm.setVisibility(View.GONE);
                break;
            case 2:
            case 3:
                pop_ok.setVisibility(View.GONE);
                btn_buy.setVisibility(View.GONE);
                btn_confirm.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
        select_price_tv = view.findViewById(R.id.select_price_tv);
        textOriginalPrice = view.findViewById(R.id.text_original_price);
        Stock_tv = view.findViewById(R.id.Stock_tv);
        choose_title = view.findViewById(R.id.choose_title);
        recyclerView = view.findViewById(R.id.sku_rv);
        pop_ok.setOnClickListener(this);
        btn_buy.setOnClickListener(this);
        btn_confirm.setOnClickListener(this);
        popDel.setOnClickListener(this);
        LinearLayoutManager llm = new LinearLayoutManager(context);
        mAdapter = new CountChooseAdapter(context);
        mAdapter.setHide(mUiData.isHide);
        recyclerView.setLayoutManager(llm);
        recyclerView.setAdapter(mAdapter);
        initData();
    }

    private void initData() {
        mAdapter.add(mUiData);
        mAdapter.notifyDataSetChanged();
    }


    /**
     * 启动popWindow
     *
     * @param view
     */
    private void configPopWindow(View view) {
        if (popupWindow == null) {
            popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            // 设置popWindow的动画效果
            popupWindow.setAnimationStyle(R.style.MyPopupWindow_anim_style);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            popupWindow.setOnDismissListener(this);// 当popWindow消失时的监听
        }
    }

    /**
     * 设置监听
     */
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    // 当popWindow消失时响应
    @Override
    public void onDismiss() {
        darkenBackground(1f);
        if (listener != null) {
            listener.cancel();
        }
    }

    /**
     * 弹窗显示的位置
     */
    public void showAsDropDown(View parent) {
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.update();
        darkenBackground(0.5f);
    }

    private boolean isShowing() {
        return popupWindow != null && popupWindow.isShowing();
    }

    /**
     * 退出弹窗
     */
    public void dismiss() {
        if (isShowing()) {
            popupWindow.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pop_ok:
                if (mAdapter.isHide()) {
                    if (isAllChoose && listener != null && mAdapter != null) {
                        dismiss();
                        listener.onClickShopping(1);
                    } else {
                        if (mIsSpecSmall) {
                            ToastUtil.showTip(context, "该商品信息不全，暂时无法购买");
                        } else {
                            ToastUtil.showTip(context, "请选择商品属性！");
                        }
                    }
                } else {
                    if (isAllChoose && listener != null && mAdapter != null && mAdapter.getStandardFootView() != null) {
                        dismiss();
                        listener.onClickShopping(mAdapter.getNumber());//.getStandardFootView()).pop_num.getText().toString()
                    } else {
                        if (mIsSpecSmall) {
                            ToastUtil.showTip(context, "该商品信息不全，暂时无法购买");
                        } else {
                            ToastUtil.showTip(context, "请选择商品属性！");
                        }
                    }
                }
                break;
            case R.id.btn_buy: {
                if (mAdapter.isHide()) {
                    if (isAllChoose && listener != null && mAdapter != null) {
                        dismiss();
                        listener.onClickBuy(1);
                    } else {
                        if (mIsSpecSmall) {
                            ToastUtil.showTip(context, "该商品信息不全，暂时无法购买");
                        } else {
                            ToastUtil.showTip(context, "请选择商品属性！");
                        }
                    }
                } else {
                    if (isAllChoose && listener != null && mAdapter != null && mAdapter.getStandardFootView() != null) {
                        dismiss();
                        listener.onClickBuy(mAdapter.getNumber());//.getStandardFootView()).pop_num.getText().toString()
                    } else {
                        if (mIsSpecSmall) {
                            ToastUtil.showTip(context, "该商品信息不全，暂时无法购买");
                        } else {
                            ToastUtil.showTip(context, "请选择商品属性！");
                        }
                    }
                }
            }
            break;
            case R.id.btn_confirm: {
                if (mAdapter.isHide()) {
                    if (isAllChoose && listener != null && mAdapter != null) {
                        dismiss();
                        if (mType == 2) {
                            listener.onClickShopping(1);
                        } else {
                            listener.onClickBuy(1);
                        }
                    } else {
                        if (mIsSpecSmall) {
                            ToastUtil.showTip(context, "该商品信息不全，暂时无法购买");
                        } else {
                            ToastUtil.showTip(context, "请选择商品属性！");
                        }
                    }
                } else {
                    if (isAllChoose && listener != null && mAdapter != null && mAdapter.getStandardFootView() != null) {
                        dismiss();
                        if (mType == 2) {
                            listener.onClickShopping(mAdapter.getNumber());//.getStandardFootView()).pop_num.getText().toString()
                        } else {
                            listener.onClickBuy(mAdapter.getNumber());//.getStandardFootView()).pop_num.getText().toString()
                        }
                    } else {
                        if (mIsSpecSmall) {
                            ToastUtil.showTip(context, "该商品信息不全，暂时无法购买");
                        } else {
                            ToastUtil.showTip(context, "请选择商品属性！");
                        }
                    }
                }
            }
            break;
            case R.id.close:
                dismiss();
                break;
            default:
                break;
        }
    }

    /**
     * 展示库存和图片还有已选规格
     *
     * @param baseSkuModel
     * @param sku
     */
    @Override
    public void showPriceAndSku(BaseSkuModel baseSkuModel, String sku) {
        //展示价格和sku
        GlideApp.with(context)
                .load(baseSkuModel.picture)
                .centerCrop()
                .skipMemoryCache(true)
                .placeholder(R.mipmap.icon_default_picture)
                .into(select_iv);
        if (null != baseSkuModel.price) {
            String price = "¥" + NumberFormatUtils.getInstance().format2Decimal(baseSkuModel.price.doubleValue());
            select_price_tv.setText(price);
        }
        if (null != baseSkuModel.originalPrice) {
            String originalPrice = "¥" + NumberFormatUtils.getInstance().format2Decimal(baseSkuModel.originalPrice.doubleValue());
            textOriginalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
            textOriginalPrice.setText(originalPrice);
        }
        choose_title.setText(sku);
        String stock = "库存" + baseSkuModel.stock + "件";
        Stock_tv.setText(stock);
        mAdapter.setState(CountChooseAdapter.STATE_Max);
        isAllChoose = sku.contains("已选： ");
    }

    public interface OnItemClickListener {
        /**
         * 设置点击确认按钮时监听接口
         */
        void onClickShopping(long num);

        void onClickBuy(long num);

        void cancel();
    }
}
